<?php

namespace app\index\controller;

use app\index\model\Consume;
use app\index\model\Sharehistory;
use app\index\model\User;
use think\Request;

class Index extends Base
{
    private function getUser()
    {
        return new User();
    }

    private function getShare()
    {
        return new \app\index\model\Share();
    }

    private function getPay()
    {
        return new \app\index\model\Pay();
    }

    private function getCounsume()
    {
        return new Consume();
    }

    private function getShareHistory()
    {
        return new Sharehistory();
    }

    public function index(Request $request)
    {
        if ($request->isGet()) {
            if (\think\Session::has("uid")) {
                return $this->redirect("home/home");
            } else {
                if ($request->param("code")) {
                    //获取code请求api
                    if (array_key_exists("appCode", $request->param())) {
                        $apiUrl = config("API_HOST") . config("GET_USERINFO_1") . $request->param("appCode")
                            . config("GET_USERINFO_2") . $request->param("code")."&saveUserInfo=1";
                        $resultInfo = json_decode($this->http_request($apiUrl), true);
                        $userInfo = json_decode($this->getWxUserInfo($resultInfo['access_token'], $resultInfo['openid']), true);
                        if (is_array($userInfo) && array_key_exists("openid", $userInfo)) {
                            //用户不存在执行注册存在获取用户信息
                            if ($user = $this->getUser()->findByKV(['openid' => $userInfo['openid'],'seller_id'=>0])) {
                                $data = [
                                    'id' => $user['id'],
                                    'last_login_time' => time(),
                                    'last_login_ip' => $request->ip()
                                ];
                                $this->getUser()->edit($data);//更新用户最新登陆时间跟地址
                                \think\Session::set("uid", $user['id']);
                            } else {
                                $pid = 0;
                                $pPath = "";//上级路径
                                if ($request->param("pid")) {
                                    //保存上级信息并遍历3级上级id  -一级-二级-三级-
                                    $pid = $request->param("pid");
                                    $pPath = $this->getUser()->getPPath($pid);
                                }
                                $data = [
                                    'openid' => $userInfo['openid'],
                                    'nickname' => $userInfo['nickname'],
                                    'reg_time' => time(),
                                    'reg_ip' => $request->ip(),
                                    'last_login_time' => time(),
                                    'last_login_ip' => $request->ip(),
                                    'pid' => $pid,
                                    'head_img_url' => $userInfo['headimgurl'],
                                    'p_path' => $pPath
                                ];
                                $userId = $this->getUser()->add($data);//添加用户并返回id
                                \think\Session::set("uid", $userId);
                            }
                            $this->redirect("home/home");
                        }
                    }
                } else {
                    $apiUrl = config("API_HOST") . config("AUTO_USER") . urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "?");
                    //进行授权
                    $url = json_decode($this->http_request($apiUrl), true)['url'];
                    header("Location:" . $url);
                    exit();
                }
            }
        }
    }


    public function getWxUserInfo($token, $openid)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $token . "&openid=" . $openid . "&lang=zh_CN";
        return $this->http_request($url);
    }

    /*
     * 写入分享明细
     * @param $user_id int |被关注者用户id
     * @param $qrcode_id string | 二维码id
     * @param $focus_nickname string |关注者id
     * @param $focus_head_img_url string |关注者微信头像
     * @param $qr_code_path string | 海报模板路径
     * @parma $price  int | 本次关注单价分为单位
     * */
    public function readDetail(Request $request)
    {
        if ($request->isPost()) {
            $data = $request->param();
            if (is_array($data) && array_key_exists("openid", $data)) {
                $data['add_time'] = time();
                return $this->getShare()->readDetailAndIncUserAmount($data) ? 200 : 500;
            } else {
                return json_encode(['404', '数据填写有误']);
            }
        }
    }

    /*
    * 获取用户提现列表(按未支付最早的订单排序)
     * @param $page int |分页
     * @param $limit int |获取多少条默认10
    * */
    public function userPayList(Request $request)
    {
        if ($request->isGet()) {
            $page = $request->param("page") ? $request->param("page") : 0;
            $limit = $request->param("limit") ? $request->param("limit") : 10;
            $userPayList = $this->getPay()->mySelectByKVPage(['status' => $request->param("status")], $page, $limit, 'asc');
            return json_encode($userPayList);
        }
    }

    /*
     * 更新用户提现订单
     * @param $id int |订单Id
     * @param $status int |订单状态
     * @param $pay_time int |支付时间戳
     * @param $wx_number string | 微信支付单号
     * @param $wx_result_msg string |返回信息
     * */
    public function updatePay(Request $request)
    {
        if ($request->isPost()) {
            if (is_numeric($request->param("id")) && is_numeric($request->param("status"))) {
                if ($this->getPay()->findById($request->param("id"))) {
                    $this->getPay()->edit($request->param());
                } else {
                    return ['code' => 404, 'msg' => '订单不存在'];
                }
            }
        }
    }

    /*
     * 添加或则获取海报关注数据
     * method $post 添加海报信息
     * @param $price int 单价 以分为单位
     * @param $qr_code_id 图片Id
     * @param $app_id 海报对应的公众号app_id
     * return 200 添加成功 301 字段缺少 500 服务器内部错误
     *
     * method get 获取海报信息
     * @param $qr_code_id 对应的海报id 或则海报id组以,切割(1,2,3,4)
     * return 200|404
     * */
    public function banner(Request $request)
    {
        $data = $request->param();
        if ($request->isPost()) {

            if (array_key_exists("price", $data)
                && array_key_exists("qr_code_id", $data)
                && array_key_exists("app_id", $data)) {
                $data = [
                    'price' => $data['price'],
                    'qr_code_id' => $data['qr_code_id'],
                    'add_time' => time(),
                    'app_id' => $data['app_id'],
                    'qr_code_path' => $data['qr_code_path'],
                    'slogan'=>array_key_exists("slogan",$data) ? $data['slogan'] : "",
                ];
                if ($this->getCounsume()->add($data)) {
                    $code = 200;
                    $result = ['code' => 200, 'msg' => '添加成功'];
                } else {
                    $code = 500;
                    $result = ['code' => '500', 'msg' => '服务器内部错误'];
                }
            } else {
                $code = 301;
                $result = ['code' => '301', 'msg' => '数据字段填写出错'];
            }
        } elseif ($request->isGet()) {
            if (array_key_exists("app_id", $data)) {
                if ($result = $this->getCounsume()->findByKV(['key' => 'app_id', 'value' => $data['app_id']], true)) {
                    $code = 200;
                } else {
                    $code = 404;
                    $result = ['code' => 404, 'msg' => '数据不存在'];
                }
            }
        }
        return json($result, $code);
    }

    /*
     * 用户关注信息
     * post|get
     * */
    public function wxfocus(Request $request)
    {
    /*    $data=array (
            'eventId' => 201,
            'appid' => 'wx672d8f96ddc2e7dd',
            'share' =>
                array (
                    'id' => 'PIE_pbGTh6o41W3pbQeqh2LaZLk',
                    'srcAppid' => 'wx97e0e09eacd7657a',
                    'redirectAppid' => 'wx672d8f96ddc2e7dd',
                ),
            'invitee' =>
                array (
                    'openid' => 'oodpV0hqSHj9Un8h-I6IrcxAMFuE',
                    'nickname' => '主刀医师',
                    'headimgUrl' => 'http://thirdwx.qlogo.cn/mmopen/PiajxSqBRaEI1VRQibYj26V4GvCKSDFdxnzp2QhNSpVBHqcCHQc1Mzf7NBvYSWicDJq3VkMBY5FG0h5EEUBV8GldQ/132',
                ),
            'inviter' =>
                array (
                    'openid' => 'o-X4Z06MySaUrKnR8PhqqKEQkXbg',
                    'nickname' => '我说这是信仰。',
                    'headimgUrl' => 'http://thirdwx.qlogo.cn/mmopen/rG15CLTG8xKegxQUk2gYOaNVR8u8OibSsntR8fbHqFic4rbGrNeEoPCvwvbnOtjLOmHagiasBZDyzo1J1t4XiaG6ycRE56qJ27h4/132',
                ),
        );
        echo json_encode($data);die();*/
        $data = $request->param();
        if ($request->isPost()) {
            $pieId = $data['share']['id'];
            if ($counsumeInfo = $this->getShareHistory()->getPriceByPieId($pieId)) {
                $openid=$data['inviter']['openid'];
                $userInfo=$this->getUser()->findByKV(['openid'=>$openid]);
                //判断二维码是否下架跟用户是否普通账号跟是否冻结
                if ($counsumeInfo['is_show'] == 1&&$userInfo['is_spread']==0&&$userInfo['is_lock']==0) {
                    //进行数据统计并计费
                    $data = [
                        'openid' => $data['inviter']['openid'],//分享者Openid
                        'qrcode_id' => $counsumeInfo['id'],
                        'focus_nickname' => $data['invitee']['nickname'],
                        'focus_head_img_url' => $data['invitee']['headimgUrl'],
                        'add_time' => time(),
                        'price' => $counsumeInfo['price']
                    ];
                    //对商户进行扣款
                    $url = config("SELLER_DEC_AMOUNT");
                    $putData = [
                        'appid' => $counsumeInfo['app_id'],
                        'money' => $counsumeInfo['price']
                    ];
                    $result = $this->http_request($url, false, "post", json_encode($putData));
                    $result == 1 ? $this->getShare()->readDetailAndIncUserAmount($data) : "";
                }
            }

        } elseif ($request->isGet()) {

        }
    }


}
